package com.charging.serviceImpl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.charging.bean.*;
import com.charging.bean.layuiBean.ResultPage;
import com.charging.bean.layuiBean.VoPage;
import com.charging.config.result.ApiResult;
import com.charging.mapper.SiteMapper;
import com.charging.service.ApiDiscountService;
import com.charging.service.SiteImageService;
import com.charging.service.SiteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * <p>
 * 站点信息 服务实现类
 * </p>
 *
 * @author 冯政尚
 * @since 2019-09-16
 */
@Service
public class SiteServiceImpl extends ServiceImpl<SiteMapper, Site> implements SiteService {

    @Autowired
    SiteImageService siteImageService;
    @Autowired
    ApiDiscountService apiDiscountService;

    /**
     * @param voPage
     * @return 后台查询
     */
    @Override
    public ResultPage<Site> selectMyPage(VoPage voPage) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1) * voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        List<Site> list = baseMapper.selectMyPage(paramMap);
        Integer count = baseMapper.countMyPage(paramMap);
        ResultPage<Site> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }


    /**
     * @param site
     * @return 多图片
     * @throws SQLException
     */
    @Override
    public ApiResult insertP(Site site) throws SQLException {
        this.save(site);
        for (int i = 0; i < site.getPids().size(); i++) {
            SiteImage siteImage = new SiteImage();
            siteImage.setId(Long.parseLong(site.getPids().get(i)));
            siteImage.setSiteId(site.getId());
            if (!siteImageService.updateById(siteImage)) {
                throw new SQLException();
            }
        }
        return ApiResult.ok();
    }


    /**
     * @param site
     * @return 修改
     * @throws SQLException
     */
    @Override
    public ApiResult updateSite(Site site) throws SQLException {
        if (site.getLongitude() == "" || site.getDimension() == "") {
            Site site1 = new Site();
            site1.setName(site.getName());
            site1.setAddress(site.getAddress());
            site1.setBrand(site.getBrand());
            site1.setDiscount(site.getDiscount());
            site1.setId(site.getId());
            if (this.updateById(site1)) {
                this.getSiteImage2(site);
            }
        } else {
            if (this.updateById(site)) {
                this.getSiteImage2(site);
            }
        }
        return ApiResult.ok();
    }

    /**
     * @param whole
     * @return 筛选
     */
    @Override
    public List<Site> screen(Integer whole,String dimension,String longitude,Integer distance ) {
        Map map = new HashMap();
        List<Site> siteList;
        if(distance!=null && distance!=0){
            map.put("whole",whole);
            map.put("distance",distance);
            map.put("dimension",dimension);
            map.put("longitude",longitude);
            siteList = baseMapper.screen1(map);
        }else{
             map.put("whole",whole);
            map.put("dimension",dimension);
            map.put("longitude",longitude);
             siteList = baseMapper.screen(map);
        }


        Map apiParam = new HashMap();
        apiParam.put("appid", Constent.CHARGE_API_appid);
        apiParam.put("latitude", dimension);
        apiParam.put("longitude", longitude);
        if(distance!=null && distance !=0){
            apiParam.put("scope", distance);//距离
        }else{
            apiParam.put("scope", "-1");//距离
        }
        apiParam.put("brand_status", "0,1,2,3");//运营状态，以逗号分隔，0:在建中，1:已建成未测试，2:已建成已测试，3:关闭中
        String result = HttpUtil.get(Constent.CHARGE_API_URL, apiParam);
        ChageApiResult chageApiResult = JSONObject.parseObject(result, ChageApiResult.class);
        //请求成功的时候
        if (chageApiResult.getError_code().equals("0")) {
            //查询设置的api接口中充电桩的优惠
            List<ApiDiscount> apiDiscounts = apiDiscountService.list();
            List<ChageApiResultData> data = chageApiResult.getData();


            //循环充电桩信息
            for (int i = 0; i < data.size(); i++) {
                //循环设置的充电桩优惠信息
                for (int j = 0; j < apiDiscounts.size(); j++) {
                    //取出当前循环的 设置的 API 充电桩优惠信息
                    ApiDiscount thisApiDiscount = apiDiscounts.get(j);
                    //如果 查询api的结果中 充电桩名称含有 设置的优惠的名称 那么设置优惠字段
                    if (thisApiDiscount.getName().equals(data.get(i).getName())) {
                        data.get(i).setDiscount(thisApiDiscount.getDiscount());
                        break;
                    }
                }
                ChageApiResultData chageApiResultData = data.get(i);
                if(whole==0){
                    Site site1 = new Site();
                    site1.setAddress(chageApiResultData.getAddress());
                    site1.setName(chageApiResultData.getName());
                    site1.setDiscount(chageApiResultData.getDiscount());
                    site1.setDimension(chageApiResultData.getLatitude());
                    site1.setLongitude(chageApiResultData.getLongitude());
                    site1.setBrand(chageApiResultData.getOperater());
                    site1.setDistance(chageApiResultData.getDistance());
                    site1.setOperater(chageApiResultData.getOperater());
                    siteList.add(site1);
                }else if(whole==1){
                    if(chageApiResultData.getDiscount()!=null){
                        Site site1 = new Site();
                        site1.setAddress(chageApiResultData.getAddress());
                        site1.setName(chageApiResultData.getName());
                        site1.setDiscount(chageApiResultData.getDiscount());
                        site1.setDimension(chageApiResultData.getLatitude());
                        site1.setLongitude(chageApiResultData.getLongitude());
                        site1.setBrand(chageApiResultData.getOperater());
                        site1.setDistance(chageApiResultData.getDistance());
                        site1.setOperater(chageApiResultData.getOperater());
                        siteList.add(site1);
                    }

            }else if(whole==2){
                    if(chageApiResultData.getDiscount()==null){
                        Site site1 = new Site();
                        site1.setAddress(chageApiResultData.getAddress());
                        site1.setName(chageApiResultData.getName());
                        site1.setDiscount(chageApiResultData.getDiscount());
                        site1.setDimension(chageApiResultData.getLatitude());
                        site1.setLongitude(chageApiResultData.getLongitude());
                        site1.setBrand(chageApiResultData.getOperater());
                        site1.setDistance(chageApiResultData.getDistance());
                        site1.setOperater(chageApiResultData.getOperater());
                        siteList.add(site1);
                    }

                }
            }
        }
        //把每一个距离拿出来把距离专程float类型在float转成Integer类型,再把它给设置到abc中按照abc比大小
        for (int i = 0; i < siteList.size(); i++) {
            float b = Float.parseFloat(siteList.get(i).getDistance());
            Integer a =  (int)b;
            siteList.get(i).setAbc(a);
        }
        listSort(siteList);
        return listSort(siteList);
    }

    public static List<Site> listSort(List<Site> list) {
        Collections.sort(list, new Comparator<Site>() {
            @Override
            public int compare(Site o1, Site o2) {
                //降序，o1,o2反过来则升序
                return o1.getAbc().compareTo(o2.getAbc());
            }
        });
        System.out.println(list);
        return list;
    }

    /**
     * @param address
     * @return 搜索
     */
    @Override
    public List<Site> sousuo(String address,String dimension, String longitude ) {
        Map map = new HashMap();
        map.put("address",address);
        map.put("dimension",dimension);
        map.put("longitude",longitude);

        List<Site> siteList = baseMapper.sousuo(map);

        Map apiParam = new HashMap();
        apiParam.put("appid", Constent.CHARGE_API_appid);
        apiParam.put("latitude", dimension);
        apiParam.put("longitude", longitude);
        apiParam.put("scope", -1);//距离
        apiParam.put("brand_status", "0,1,2,3");//运营状态，以逗号分隔，0:在建中，1:已建成未测试，2:已建成已测试，3:关闭中
        String result = HttpUtil.get(Constent.CHARGE_API_URL, apiParam);
        ChageApiResult chageApiResult = JSONObject.parseObject(result, ChageApiResult.class);
        //请求成功的时候
        if (chageApiResult.getError_code().equals("0")) {
            //查询设置的api接口中充电桩的优惠
            List<ApiDiscount> apiDiscounts = apiDiscountService.list();
            List<ChageApiResultData> data = chageApiResult.getData();


            //循环充电桩信息
            for (int i = 0; i < data.size(); i++) {
                //循环设置的充电桩优惠信息
                for (int j = 0; j < apiDiscounts.size(); j++) {
                    //取出当前循环的 设置的 API 充电桩优惠信息
                    ApiDiscount thisApiDiscount = apiDiscounts.get(j);
                    //如果 查询api的结果中 充电桩名称含有 设置的优惠的名称 那么设置优惠字段
                    if (thisApiDiscount.getName().equals(data.get(i).getName())) {
                        data.get(i).setDiscount(thisApiDiscount.getDiscount());
                        break;
                    }
                }
                ChageApiResultData chageApiResultData = data.get(i);
                System.out.println("chageApiResultData:"+chageApiResultData.getName()+",---,"+chageApiResultData.getAddress());

                Pattern regex = Pattern.compile(address);
                boolean a = regex.matcher(chageApiResultData.getAddress()).find();
                if(a){
                    Site site1 = new Site();
                    site1.setAddress(chageApiResultData.getAddress());
                    site1.setName(chageApiResultData.getName());
                    site1.setDiscount(chageApiResultData.getDiscount());
                    site1.setDimension(chageApiResultData.getLatitude());
                    site1.setLongitude(chageApiResultData.getLongitude());
                    site1.setBrand(chageApiResultData.getOperater());
                    site1.setDistance(chageApiResultData.getDistance());
                    site1.setOperater(chageApiResultData.getOperater());
                    siteList.add(site1);
                }else{
                    return siteList;
                }



            }
        }

//把每一个距离拿出来把距离专程float类型在float转成Integer类型,再把它给设置到abc中按照abc比大小
        for (int i = 0; i < siteList.size(); i++) {
            float b = Float.parseFloat(siteList.get(i).getDistance());
            Integer a =  (int)b;
            siteList.get(i).setAbc(a);
        }
        listSort(siteList);
        return listSort(siteList);
    }

    /**
     * @param name
     * @return 详情
     */
    @Override
    public List<Site> details(String name,String dimension, String longitude) {
        List<Site> list = baseMapper.details(name);
        if(list.size()==0){
            Map apiParam = new HashMap();
            apiParam.put("appid", Constent.CHARGE_API_appid);
            apiParam.put("latitude", dimension);
            apiParam.put("longitude", longitude);
            apiParam.put("scope", "-1");//距离
            apiParam.put("brand_status", "0,1,2,3");//运营状态，以逗号分隔，0:在建中，1:已建成未测试，2:已建成已测试，3:关闭中
            String result = HttpUtil.get(Constent.CHARGE_API_URL, apiParam);
            ChageApiResult chageApiResult = JSONObject.parseObject(result, ChageApiResult.class);
            //请求成功的时候
            if (chageApiResult.getError_code().equals("0")) {
                //查询设置的api接口中充电桩的优惠
                List<ApiDiscount> apiDiscounts = apiDiscountService.list();
                List<ChageApiResultData> data = chageApiResult.getData();
                //循环充电桩信息
                for (int i = 0; i < data.size(); i++) {
                    //循环设置的充电桩优惠信息
                    for (int j = 0; j < apiDiscounts.size(); j++) {
                        //取出当前循环的 设置的 API 充电桩优惠信息
                        ApiDiscount thisApiDiscount = apiDiscounts.get(j);
                        //如果 查询api的结果中 充电桩名称含有 设置的优惠的名称 那么设置优惠字段
                        if (thisApiDiscount.getName().equals(data.get(i).getName())) {
                            data.get(i).setDiscount(thisApiDiscount.getDiscount());
                            break;
                        }
                    }
                    ChageApiResultData chageApiResultData = data.get(i);
                    if(chageApiResultData.getName().equals(name)){
                        Site site1 = new Site();
                        site1.setAddress(chageApiResultData.getAddress());
                        site1.setName(chageApiResultData.getName());
                        site1.setDiscount(chageApiResultData.getDiscount());
                        site1.setDimension(chageApiResultData.getLatitude());
                        site1.setLongitude(chageApiResultData.getLongitude());
                        site1.setBrand(chageApiResultData.getOperater());
                        site1.setDistance(chageApiResultData.getDistance());
                        site1.setOperater(chageApiResultData.getOperater());
                        list.add(site1);
                    }

                }
                return list;
            }
        }


        return baseMapper.details(name);
    }

    @Override
    public ApiResult findSiteByLocal(String dimension, String longitude) {
        List<Site> dbSites = baseMapper.findSiteByLocal(dimension, longitude);

        Map apiParam = new HashMap();
        apiParam.put("appid", Constent.CHARGE_API_appid);
        apiParam.put("latitude", dimension);
        apiParam.put("longitude", longitude);
        apiParam.put("scope", "-1");//距离
        apiParam.put("brand_status", "0,1,2,3");//运营状态，以逗号分隔，0:在建中，1:已建成未测试，2:已建成已测试，3:关闭中
        String result = HttpUtil.get(Constent.CHARGE_API_URL, apiParam);
        ChageApiResult chageApiResult = JSONObject.parseObject(result, ChageApiResult.class);
        //请求成功的时候
        if (chageApiResult.getError_code().equals("0")) {
            //查询设置的api接口中充电桩的优惠
            List<ApiDiscount> apiDiscounts = apiDiscountService.list();
            List<ChageApiResultData> data = chageApiResult.getData();
            //循环充电桩信息
            for (int i = 0; i < data.size(); i++) {
                //循环设置的充电桩优惠信息
                for (int j = 0; j < apiDiscounts.size(); j++) {
                    //取出当前循环的 设置的 API 充电桩优惠信息
                    ApiDiscount thisApiDiscount = apiDiscounts.get(j);
                    //如果 查询api的结果中 充电桩名称含有 设置的优惠的名称 那么设置优惠字段
                    if (thisApiDiscount.getName().equals(data.get(i).getName())) {
                        data.get(i).setDiscount(thisApiDiscount.getDiscount());
                        break;
                    }
                }
                ChageApiResultData chageApiResultData = data.get(i);
                Site site1 = new Site();
                site1.setAddress(chageApiResultData.getAddress());
                site1.setName(chageApiResultData.getName());
                site1.setDiscount(chageApiResultData.getDiscount());
                site1.setDimension(chageApiResultData.getLatitude());
                site1.setLongitude(chageApiResultData.getLongitude());
                site1.setBrand(chageApiResultData.getOperater());
                site1.setDistance(chageApiResultData.getDistance());
                site1.setOperater(chageApiResultData.getOperater());
                dbSites.add(site1);
            }
            //把每一个距离拿出来把距离专程float类型在float转成Integer类型,再把它给设置到abc中按照abc比大小
            for (int i = 0; i < dbSites.size(); i++) {
                float b = Float.parseFloat(dbSites.get(i).getDistance());
                Integer a =  (int)b;
                dbSites.get(i).setAbc(a);
            }
            listSort(dbSites);
            return ApiResult.ok(listSort(dbSites));
        }
        return ApiResult.fail();
    }


    /**
     * @param voPage
     * @return 查询api接口数据
     */
    @Override
    public ResultPage<ChageApiResultData> selectApiMyPage(VoPage voPage, String lng, String lat) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1) * voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        Map apiParam = new HashMap();
        apiParam.put("appid", Constent.CHARGE_API_appid);
        apiParam.put("latitude", lat); //维度
        apiParam.put("longitude", lng); //经度
        apiParam.put("scope", "-1");//距离
        apiParam.put("brand_status", "0,1,2,3");//运营状态，以逗号分隔，0:在建中，1:已建成未测试，2:已建成已测试，3:关闭中
        String result = HttpUtil.get(Constent.CHARGE_API_URL, apiParam);
        //System.out.println("result:" + result);
        //把从api查询出来的数据转成实体类
        ChageApiResult chageApiResult = JSONObject.parseObject(result, ChageApiResult.class);
        //如果相应的code为0酒分页执行,否则就返回无数据
        if (chageApiResult.getError_code().equals("0")) {
            List<ChageApiResultData> data = chageApiResult.getData();
            Integer count = data.size();
            ResultPage<ChageApiResultData> resultPage = new ResultPage<>();
            resultPage.setCode(0);
            resultPage.setCount(count);
            resultPage.setMsg("成功");
            resultPage.setData(data);
            return resultPage;
        }
        List<ChageApiResultData> data = null;
        Integer count = 0;
        ResultPage<ChageApiResultData> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(data);
        return resultPage;
    }




    public void getSiteImage(Site site) throws SQLException {
        for (int i = 0; i < site.getPids().size(); i++) {
            SiteImage siteImage = new SiteImage();
            siteImage.setId(Long.parseLong(site.getPids().get(i)));
            siteImage.setSiteId(site.getId());
            if (!siteImageService.updateById(siteImage)) {
                throw new SQLException();
            }
        }
    }


    public ApiResult getSiteImage2(Site site) throws SQLException {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("site_id", site.getId());
        List<SiteImage> siteImages = siteImageService.list(queryWrapper);
        for (int j = 0; j < siteImages.size(); j++) {
            if (!siteImageService.removeById(siteImages.get(j).getId())) {
                return ApiResult.fail("修改失败");
            }
        }
        getSiteImage(site);
        return ApiResult.ok();
    }

}
